#define _CRT_SECURE_NO_WARNINGS 1

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;

    Node() {}

    Node(int _val) {
        val = _val;
        left = NULL;
        right = NULL;
    }

    Node(int _val, Node* _left, Node* _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/
class Solution
{
public:
    Node* treeToDoublyList(Node* root)
    {
        if (root == nullptr) {
            return nullptr;
        }

        Node* start = root;
        while (start->left != nullptr) {
            start = start->left;
        }

        Node* end = root;
        while (end->right != nullptr) {
            end = end->right;
        }

        Node* prev = nullptr;
        _BuildList(root, prev);

        start->left = end;
        end->right = start;

        return start;
    }

private:
    void _BuildList(Node* cur, Node*& prev)
    {
        if (cur == nullptr) {
            return;
        }

        _BuildList(cur->left, prev);
        cur->left = prev;
        if (prev != nullptr) {
            prev->right = cur;
        }
        prev = cur;
        _BuildList(cur->right, prev);
    }
};